/*
* Copyright (C) 2020 ~ 2024 chaigec All Rights Reserved.
*
* Author:     chaigec <chaigec@163.com>
* Maintainer: chaigec <chaigec@163.com>

 * Use of this source code is governed by MIT license that can be found in the
 * LICENSE file in the root of the source tree. All contributing project authors
 * may be found in the AUTHORS file in the root of the source tree.
*/

#include "MkGbConsumer.h"
#include "MkPs/MkPsMuxer.h"
#include "MkMedia/MkMediaSource.h"
#include "MkRtp/MkRtp.h"

CMkGbConsume::CMkGbConsume()
    : CMkMediaConsume(MkMediaConsumeGb)
{

}

Uint32 CMkGbConsume::ConsumeEsPacket(CMkMediaSource* pSource, const MkEsPacket& EsPacket, Uint8* pBuf, Uint32 nLen)
{
    Uint32 ErrorCode = InvalidParams;
    CMkBufferList BufList;
    Uint32 nUsed = 0;
    CMkPsMuxer::PacketEsPacket(pSource->GetVideoParam(), pSource->GetAudioParam(), EsPacket, pBuf, nLen, nUsed, BufList);

    CMkGbConsumer* pGbConsumer = nullptr;
    MkMap<MkString, CMkMediaConsumer*>::iterator it = GetMapConsumer().begin();
    for (; it != GetMapConsumer().end(); it++) {
        pGbConsumer = dynamic_cast<CMkGbConsumer*>(it->second);
        if (!pGbConsumer) {
            continue;
        }
        if (pGbConsumer->IsFirstSend()) {
            MkVector<MkCacheEsPacket>::const_iterator itCache = pSource->GetCacheEsPacket().begin();
            for (; itCache != pSource->GetCacheEsPacket().end(); itCache++) {
                MkEsPacket CacheEsPacket;
                CMkMediaUtil::ReadCachePacket(*itCache, CacheEsPacket);
                Uint32 CurUsed = 0;
                CMkBufferList BufList;
                CMkPsMuxer::PacketEsPacket(pSource->GetVideoParam(), pSource->GetAudioParam(), CacheEsPacket, pBuf + nUsed, nLen - nUsed, CurUsed, BufList);
                pGbConsumer->ConsumeBuf(BufList, CacheEsPacket.Pts);
            }
            pGbConsumer->SetFirstSend(FALSE);
        }
        pGbConsumer->ConsumeBuf(BufList, EsPacket.Pts);
    }

    return NoneError;
}

CMkGbConsumer::CMkGbConsumer(const Uint32& Ssrc, CMkRtp* pRtp)
    : CMkMediaConsumer(MkMediaConsumeGb)
    , m_Ssrc(Ssrc)
    , m_pRtp(pRtp)
{

}

Uint32 CMkGbConsumer::ConsumeBuf(const CMkBufferList& BufList, Uint32 TimeStamp)
{
    AddSendBytes(BufList.GetTatolLen());
    if (m_pRtp) {
        m_pRtp->SendBuffer(BufList, m_Ssrc, TimeStamp);
    }
    return NoneError;
}

void CMkGbConsumer::Release()
{
    if (m_pRtp) {
        m_pRtp->DeleteRemoter(m_Ssrc);
    }
}


CMkGbConsume::~CMkGbConsume()
{

}

CMkGbConsumer::~CMkGbConsumer()
{

}